package com.group3.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.group3.dao.AdminMapper;
import com.group3.domain.Admin;
import com.group3.domain.AdminExample;
import com.group3.exception.BusinessException;
import com.group3.exception.ExceptionEnum;
import com.group3.pojo.UpdatePassword;
import com.group3.service.AdminService;
import com.group3.utils.JWTUtils;
import com.group3.utils.Md5;
import com.group3.utils.Result;
import com.group3.utils.ResultUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Override
    @Transactional
    public Result updatePas(String token, UpdatePassword updatePassword) {

        updatePassword.setPassword(Md5.encodeByMD5(updatePassword.getPassword()));//为获取到的密码加密
        updatePassword.setNewPassword(Md5.encodeByMD5(updatePassword.getNewPassword()));

        DecodedJWT jwt = JWTUtils.getToken(token);//获取token
        String account = jwt.getClaim("id").asString();//获取登录学生的id

        //判断原密码是否错误
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andPasswordEqualTo(updatePassword.getPassword());

        List<Admin> admins = adminMapper.selectByExample(adminExample);

        if (admins.size() < 1){
            throw new BusinessException(ExceptionEnum.OLD_PASSWORD_ERR);
        }

        Admin admin = new Admin();
        admin.setAdminAccount(account);
        admin.setPassword(updatePassword.getNewPassword());


        int rs = adminMapper.updateByPrimaryKeySelective(admin);

        return rs > 0? ResultUtil.success("密码修改成功"):ResultUtil.error();
    }
}
